from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS  # Импортируем CORS

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///dental_analysis.db'
db = SQLAlchemy(app)
CORS(app)  # Включаем CORS для всего приложения

class PatientData(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    district = db.Column(db.String(50), nullable=False)
    age = db.Column(db.Integer, nullable=False)
    gender = db.Column(db.String(10), nullable=False)
    tooth_conditions = db.Column(db.String, nullable=False)
    kp_index = db.Column(db.Float, nullable=False)  # Добавляем поле для хранения индекса КПУ

    def __repr__(self):
        return f'<PatientData {self.id}>'

@app.route('/add_patient_data', methods=['POST'])
def add_patient_data():
    data = request.get_json()
    tooth_conditions = ','.join([f'{key}:{value}' for key, value in data['tooth_conditions'].items()])
    kp_index = data['kp_index']  # Получаем индекс КПУ из данных
    
    new_patient = PatientData(
        district=data['district'],
        age=data['age'],
        gender=data['gender'],
        tooth_conditions=tooth_conditions,
        kp_index=kp_index  # Сохраняем индекс КПУ
    )
    db.session.add(new_patient)
    db.session.commit()
    return jsonify({'message': 'Data added successfully'}), 201

@app.route('/get_kp_index_data/<district>', methods=['GET'])
def get_kp_index_data(district):
    patients = PatientData.query.filter_by(district=district).all()
    kp_indices = [p.kp_index for p in patients]  # Используем сохраненные индексы КПУ
    return jsonify({'kp_indices': kp_indices})

def calculate_kp_index(tooth_conditions):
    conditions = tooth_conditions.split(',')
    carious = conditions.count('Кариес')
    filled = conditions.count('Запломбирован')
    missing = conditions.count('Удален')
    return carious + filled + missing

if __name__ == '__main__':
    with app.app_context():
        db.create_all()  # Создаем таблицы в базе данных
    app.run(host='5.23.53.132', port=5000, debug=False)
